<?php

namespace app\index\controller\ad;

use app\index\dao\TempTokenDao;
use app\index\traits\CaptchaTrait;
use app\index\traits\TempTokenCheckTrait;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use ShidianUtil\Utils\CheckUtil;
use think\exception\ValidateException;
use think\Request;

/**
 * Class Number
 * @package app\index\controller\ad
 */
class TempSession
{
    use CaptchaTrait;
    use TempTokenCheckTrait;

    private Request $request;
    private TempTokenDao $tempTokenDao;

    public function __construct(Request $request, TempTokenDao $tempTokenDao)
    {
        $this->request = $request;
        $this->tempTokenDao = $tempTokenDao;
    }

    /**
     * 临时保存手机号
     * @return ApiResponse
     * @url /ad/temp_session/save
     */
    public function save(): ApiResponse
    {

        $phone = $this->request->param('phone');
        $captcha = $this->request->param('captcha');
        $inviteCode = $this->request->param('inviteCode');

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if (is_blank($phone)) {
            throw new ValidateException('请输入手机号码');
        }

        if (!CheckUtil::isPhoneNumber($phone)) {
            throw new ValidateException('请输入正确的手机号码');
        }

        // 验证验证码
        $this->checkCaptcha(CAPTCHA_AD, $phone, $captcha);

        // 临时token
        $tempToken = $this->encodeTempToken($phone, $inviteCode);

        $data = [
            'phone' => $phone,
            'inviteCode' => $inviteCode,
            'tempToken' => $tempToken,
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
        ];
        $this->tempTokenDao->insertActive($data);

        $data = [
            'tempToken' => $tempToken,
        ];

        return ApiResponse::success($data);
    }
}
